<template>
  <el-breadcrumb separator="/" id="breadcrumb">
    <el-breadcrumb-item :to="{ path: '/home/system' }">系统设置</el-breadcrumb-item>
    <el-breadcrumb-item>任免管理</el-breadcrumb-item>
  </el-breadcrumb>
  <el-row>
    <el-col :span="4" class="main-left">
      <el-input v-model="deptKeyword" placeholder="部门搜索"/>
      <main>
        <el-tree :filter="'研发'" @node-click="treeClick" :data="deptTree" default-expand-all
                 :props='{value: "id", label: "label"}'/>
      </main>
    </el-col>
    <el-col :span="20">
      <tableList
          :dict="dict"
          :tableData="tableData"
          :tableConfig="tableConfig"
          @doit="tableDoit"
      />
    </el-col>
  </el-row>

  <drawer
      :dict="dict"
      :drawerData="drawerData"
      :drawerConfig="drawerConfig"
      @doit="drawerDoit"
  />
  <deleteDialog
      :deleteDialogConfig="deleteDialogConfig"
  />
</template>

<script setup lang="ts">
import tableList from '@/components/TableList.vue'
import drawer from '@/components/Drawer.vue'
import deleteDialog from '@/components/DeleteDialog.vue'
import {ref, reactive, onMounted} from 'vue'
import { getPostList} from "@/api/system/post.ts";
import {addUser, delUser, editUser, getUserList, getUserSelects, resetPwdUser} from "@/api/system/user.ts";
import {createDict} from "@/common/dict.ts";
import {ElMessage} from 'element-plus'
import {numberToString} from "@/common/index.ts";
import config from '@/config.ts'
//table
import {table_config} from './tableConfig.js'

let tableConfig = reactive(table_config()) //表格配置
let tableData = ref([]) //表格数据
let search:any = reactive({})
// let deptKey = ref('')
let deptTree = ref([])
let deptKeyword = ref('')
//drawer
import {drawer_config} from './drawerConfig.js'
import {getDeptTree} from "@/api/system/dept.ts";


let drawerConfig = reactive(drawer_config()) //抽屉配置
const thing = { //新建的实体
  "userId": null,
  "deptId": null,
  "userName": "",
  "password":"",
  "nickName": "",
  "phonenumber": "",
  "email": "",
  "sex": "0",
  "status": "0",
  "remark": "",
}
let drawerData = ref({})
let deleteDialogConfig:any = ref({
  visible: false,
  message: "是否删除",
  alertTitle: "警告",
  confirmText: "确认",
  cancelText: "取消",
  confirmFunction: () => {
  },
  cancelFunction: () => {
  }
}) //删除对话框配置
const dictKey = ['sys_normal_disable', 'sys_user_sex','political_outlook','highest_educational','highest_major'] //本页面所需要的字典值
let dict = reactive({})

onMounted(async () => {
  dict = await createDict(dictKey) //模块字典值初始化
  await dataInit() //数据初始化
})

//数据初始化
async function dataInit() {
  //获取部门tree
  deptTree.value = await getDeptTree()
  //分页数据加载
  let page = {
    pageNum: tableConfig.pageNum,
    pageSize: tableConfig.pageSize,
  }
  let data = Object.assign(page, search)
  //数据初始化
  let postList = await getPostList(data)
  let r = await getUserList(data)
  tableData.value = r.data.map((item) => {
    item.postIds.map((itemIn)=>{
      postList.data.map((itemInto)=>{
        if(itemInto.postId == itemIn){
          item.postIdsValue = item.postIdsValue?(item.postIdsValue+' '+itemInto.postName):itemInto.postName
        }
      })
    })
    return item
  });
  tableConfig.total = r.total
  //格式化添加修改的表单数据
  drawerConfig.form[9].options = deptTree.value
}

//点击左侧树节点
function treeClick(e) {
  // @ts-ignore
  tell.log('树节点点击', e)
  search.deptId = e.id
  dataInit()
}

let selection:any = [] //多选的数据
//table事件调度中心
async function tableDoit(e) {
  const eventName = e.eventName, val = e.value
  // @ts-ignore
  tell.log('表格事件分析', eventName, val)
  switch (eventName) {
    case 'refresh': //数据重新加载
      await dataInit()
      break;
    case 'add': //新增数据
    
      drawerData.value = Object.assign({}, thing)
      const selectAdd = await getUserSelects("")
      drawerConfig.form[12].options = deptTree.value
      drawerConfig.form[13].options = await numberToString(selectAdd.posts,'postId')
      drawerConfig.form[14].options = await numberToString(selectAdd.roles,'roleId')
      drawerConfig.show = true
      break;
    case 'edit': //编辑数据
      let tmpVal = Object.assign({}, val) //深度复制，防止污染
      //获取下拉选择
      const selectRs = await getUserSelects(val.userId)
      tmpVal.postIds = selectRs.postIds
      tmpVal.roleIds = selectRs.roleIds
      // tmpVal.depts = deptTree.value
      drawerConfig.form[12].options = deptTree.value
      drawerConfig.form[13].options = await numberToString(selectRs.posts,'postId')
      drawerConfig.form[14].options = await numberToString(selectRs.roles,'roleId')
      drawerData.value = tmpVal
      drawerConfig.show = true
      break;
    case 'selectionChange': //批量选择
      selection = val
      break;
    case 'reset': //重置搜索
        deleteDialogConfig.value = {
          visible: true,
          message: `初始密码后，密码为'${config.userResetPwd}'，请尽快修改密码`,
          alertTitle: "警告",
          confirmText: "确认",
          cancelText: "取消",
          confirmFunction: async () => {
            if (val.userName == 'admin') {
              ElMessage({
                type: 'danger',
                // @ts-ignore
                message: '不能删除超级管理员',
              })
            }else{
              resetPwdUser(val.userId)
              ElMessage({
                message: `密码已经初始化，新密码是'${config.userResetPwd}'`,
                type: 'success',
              })
            }
            deleteDialogConfig.value.visible = false
          },
        }
      break;
    case 'delAll':
      if (selection.length > 0) {
        deleteDialogConfig.value = {
          visible: true,
          message: "是否批量删除选择的数据。请再次确认！",
          alertTitle: "警告",
          confirmText: "确认",
          cancelText: "取消",
          confirmFunction: async () => {
            for (let i in selection) {
              await delUser(selection[i].userId)
            }
            deleteDialogConfig.value.visible = false
            dataInit()
            ElMessage({
              message: '删除成功，用户功能待用户刷新后才能正常使用.',
              type: 'success',
            })
          },
        }
      }
      break;
    case 'search': //搜索
      search = val
      dataInit()
      break;
    case 'handleSizeChange':
      tableConfig.pageSize = val
      dataInit()
      break
    case 'handleCurrentChange': //点击分页
      tableConfig.pageNum = val
      dataInit()
      break
    default:
      // @ts-ignore
      tell.log('未知组件事件', eventName, val)
  }
}

//drawer事件调度中心
async function drawerDoit(e) {
  const eventName = e.eventName, val = e.value
  // @ts-ignore
  tell.log('抽屉事件分析', eventName, val)
  switch (eventName) {
    case 'save': //保存数据
      let result:any = ""
      if (val.userId) {
        result = await editUser(val)
      } else {
        result = await addUser(val)
      }

      if (result.code == 200) {
        dataInit()
        ElMessage({
          message: '新增成功',
          type: 'success',
        })
        drawerConfig.show = false
      } else {
        ElMessage({
          message: '数据错误，请管理员查看问题',
          type: 'warning',
        })
      }

      break;
    case 'close': //关闭弹窗
      drawerConfig.show = false
      break;
    default:
      // @ts-ignore
      tell.log('未知组件事件', eventName, val)
  }
}
</script>
<style scoped lang="scss">
.content {
  padding-top: 20px;
}
</style>